package com.android.antelopeapp.activity;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.antelopeapp.R;
import com.android.antelopeapp.fragment.CNHomeFragment;
import com.android.antelopeapp.fragment.CommodityFragment;
import com.android.antelopeapp.fragment.FragmentFactory;
import com.android.antelopeapp.utils.NetworkUtils;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;



public class MainActivity extends BaseActivity {
    private static String CUR_FM_TAG ;
    private static final String HOME_FM_TAG="CNHomeFragment";
    private static final String COMMODITY_FM_TAG="CommodityFragment";
    private MainTabbar tabbar;
    private MainActivity instance;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        CUR_FM_TAG=HOME_FM_TAG;
        setOverflowShowingAlways();
        
        /*
         * 初始化第一个fragment
         * 这部分工作在inittabhost中实现
        Fragment fm = new CNHomeFragment();
        getSupportFragmentManager().beginTransaction()
        .add(R.id.main_fragment_container, fm,CUR_FM_TAG).commit();
        */
           instance=this;
           initTabHost();
           /**发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率**/
           MobclickAgent.updateOnlineConfig( this );
           /** 设置是否对日志信息进行加密, 默认false(不加密). */
           AnalyticsConfig.enableEncrypt(true);

    }

    public Fragment getCurFragment() {
        return getSupportFragmentManager().findFragmentByTag(CUR_FM_TAG);
    }

    /**
     * 初始化下方tab栏
     * 选择第一个tab，并初始化第一个fragment
     */
    private void initTabHost() {
        tabbar = new MainTabbar((LinearLayout) findViewById(R.id.main_tabbar)) {
            @Override
            protected void onSelectedChanged(int index) {
                /**
                 * 在这里进行网络是否连接的判断，若没有联网则加载一个空白页面而不要加载对应的东西
                 */
                    Fragment curFM = getCurFragment();//得到当前的fm
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    //   Fragment nextFM = FragmentFactory.getInstanceByTabId(index);
                    String fmName=getFragmentNameById(index);
                    Fragment nextFM=getSupportFragmentManager().findFragmentByTag(fmName);
                    if(nextFM==null){
                        nextFM=FragmentFactory.getInstanceByTabId(index);
                    }
                    //得到了下一个fragment
                    CUR_FM_TAG=fmName;

                    if (curFM == null) {
                        //如果当前为空
                        transaction.add(R.id.main_fragment_container, nextFM, fmName).commit();
                        Log.v("fragment test","not added");
                    } else if (curFM!=nextFM) {
                        //如果点击了当前同一个按钮则什么都不做,否则判断一下是否已经被添加过
                        if(!nextFM.isAdded()){
                            //没有被添加过
                            transaction.hide(curFM).add(R.id.main_fragment_container,nextFM,fmName).commit();
                            Log.v("fragment test","not added");
                        }else{
                            //已经添加过
                            transaction.hide(curFM).show(nextFM).commit();
                            if(nextFM instanceof CommodityFragment){
                                ((CommodityFragment) nextFM).judgeReload();
                            }
                            /**
                            if(nextFM instanceof CNHomeFragment){
                                ((CNHomeFragment) nextFM).reJudgeNetwork();
                            }**/
                            Log.v("fragment test","already added");
                        }
                    }
                    //todo 测试用，需要删除
                /*
                if (index == 3) {
                    showLogin(null);
                } else if (index == 2) {
                    ActivityManager.startChoosePicActivity(MainActivity.this);
                    //showItemDetail(null);
                }
                */
                }


        };
        String[] texts = getResources().getStringArray(R.array.tab_texts);
        TypedArray imgs = getResources().obtainTypedArray(R.array.tab_imgs);
        tabbar.init(texts, imgs);
        imgs.recycle();

        //选择第一个tab
        tabbar.select(0);
    }

    private String getFragmentNameById(int id){
        switch (id){
            case 0:
                return HOME_FM_TAG;
            case 1:
                return COMMODITY_FM_TAG;
            default:
                return HOME_FM_TAG;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        /*
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)MenuItemCompat.getActionView(searchItem);
         */
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                toast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 用于维护下方的tab
     */
    abstract public static class MainTabbar {
        private LinearLayout tablayout;
        private int selectedIndex = -1;
        private List<ImageView> imgViews;

        public MainTabbar(LinearLayout linlayout) {
            this.tablayout = linlayout;
        }

        public int getSelectedIndex() {
            return selectedIndex;
        }

        public int getSize() {
            return imgViews.size();
        }

        public void init(String[] texts, TypedArray imgs) {
            imgViews = new ArrayList<>(imgs.length());
            for (int i = 0; i < texts.length; i++) {
                final int index = i;
                View v = tablayout.getChildAt(i);
                ImageView timg = (ImageView) v.findViewById(R.id.tab_btn_img);

                timg.setImageDrawable(imgs.getDrawable(i));

                imgViews.add(timg);

                v.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        select(index);
                    }
                });
            }
        }

        /**
         * 取消选择的状态
         */
        private void unSelect(final int index) {
            if (index != -1) {
                imgViews.get(index).setSelected(false);
            }
        }

        /**
         * 选择某一tab
         */
        protected void select(final int index) {
            if (index != selectedIndex) {
                imgViews.get(index).setSelected(true);
                unSelect(selectedIndex);
                selectedIndex = index;
                onSelectedChanged(index);
            }
        }

        abstract protected void onSelectedChanged(int index);
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
